package cn.buk.tms.eotms.service;

import cn.buk.tms.eotms.dao.TrainOrderDao;
import cn.buk.tms.eotms.dto.TrainOrderDto;
import cn.buk.tms.eotms.dto.TrainRefundOrderDto;
import cn.buk.tms.eotms.entity.TrainOrder;
import cn.buk.tms.eotms.entity.TrainRefundOrder;
import cn.buk.tms.eotms.sc.TrainOrderSearchCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TrainOrderServiceImpl extends BaseAbstractService implements TrainOrderService {

  @Autowired
  private TrainOrderDao trainOrderDao;

  @Override
  public List<TrainOrderDto> searchTrainOrders(int userId, TrainOrderSearchCriteria sc) {
    final int ownerId = getOwnerIdByUserId(userId);
    final int customerId = getCustomerIdByUserId(userId);

    List<TrainOrder> orders = trainOrderDao.searchTrainOrders(ownerId, customerId, sc);

    List<TrainOrderDto> dtos = new ArrayList<>();
    for(TrainOrder order: orders) {
      dtos.add(TrainOrderDto.createByTrainOrder(order));
    }

    return dtos;
  }

  @Override
  public TrainOrderDto getTrainOrderById(int userId, int orderId) {
    final int ownerId = getOwnerIdByUserId(userId);
    final int customerId = getCustomerIdByUserId(userId);

    TrainOrder o = trainOrderDao.getTrainOrderById(orderId);

    if (o == null) {
      return null;
    }

    if (o.getEnterpriseId() != ownerId || o.getCustomer().getId() != customerId) {
      return null;
    }

    return TrainOrderDto.createByTrainOrder(o);
  }

  @Override
  public List<TrainRefundOrderDto> searchTrainRefundOrders(int userId, TrainOrderSearchCriteria sc) {
    final int ownerId = getOwnerIdByUserId(userId);
    final int customerId = getCustomerIdByUserId(userId);

    List<TrainRefundOrder> orders = trainOrderDao.searchTrainRefundOrders(ownerId, customerId, sc);

    List<TrainRefundOrderDto> dtos = new ArrayList<>();
    for(TrainRefundOrder order: orders) {
      dtos.add(TrainRefundOrderDto.createByOrder(order));
    }

    return dtos;
  }

  @Override
  public TrainRefundOrderDto getTrainRefundOrderById(int userId, int orderId) {
    final int ownerId = getOwnerIdByUserId(userId);
    final int customerId = getCustomerIdByUserId(userId);

    TrainRefundOrder o = trainOrderDao.getTrainRefundOrderById(orderId);

    if (o == null) {
      return null;
    }

    if (o.getEnterpriseId() != ownerId || o.getCustomer().getId() != customerId) {
      return null;
    }

    return TrainRefundOrderDto.createByOrder(o);
  }
}
